package com.onenine.app.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.faceunity.effect.EffectDataMgr;
import com.faceunity.entity.Mask;
import com.faceunity.entity.MaskListEvent;
import com.onenine.app.R;
import com.onenine.app.activity.GameRunningTextActivity;
import com.onenine.app.activity.LoginActivity;
import com.onenine.app.activity.PrivateMessageActivity;
import com.onenine.app.activity.SingleVideoCallActivity;
import com.onenine.app.db.DataManager;
import com.onenine.app.event.AppUpdateEvent;
import com.onenine.app.event.FriendRelationEvent;
import com.onenine.app.event.GameMediaEvent;
import com.onenine.app.event.MessageCountEvent;
import com.onenine.app.event.MessageNotifyEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.event.RefreshMessageEvent;
import com.onenine.app.model.AMapLocationItem;
import com.onenine.app.model.AppUpdateItem;
import com.onenine.app.model.FriendAddMessage;
import com.onenine.app.model.MaskItem;
import com.onenine.app.model.SpcCount;
import com.onenine.app.request.AppUdateRequest;
import com.onenine.app.request.ClearMsgRequest;
import com.onenine.app.request.CommonRequest;
import com.onenine.app.request.ConvertUidRequest;
import com.onenine.app.request.FriendRelationRequest;
import com.onenine.app.request.GetMaskRequest;
import com.onenine.app.request.PostLikeRequest;
import com.onenine.app.request.RelationRequest;
import com.onenine.app.request.UploadLocationRequest;
import com.onenine.app.response.AppUpdateResponse;
import com.onenine.app.response.BlnResponse;
import com.onenine.app.response.ChatGiftResponse;
import com.onenine.app.response.ConvertUidResponse;
import com.onenine.app.response.CoteriesResponse;
import com.onenine.app.response.FriendIdResponse;
import com.onenine.app.response.GameCategoryResponse;
import com.onenine.app.response.GetMaskResponse;
import com.onenine.app.response.UserInfoResponse;
import com.onenine.app.view.GameOptionView;
import com.onenine.app.view.dialog.AppUpdateDialog;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.message.MsgListAdapter;
import com.onenine.chat.model.LMessage;
import com.onenine.chat.rongcloud.RcConnector;
import com.onenine.chat.rongcloud.RcImMgr;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.chat.rongcloud.RongCallAction;
import com.onenine.chat.rongcloud.RongVoIPIntent;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.AppUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.rong.calllib.IRongReceivedCallListener;
import io.rong.calllib.RongCallClient;
import io.rong.calllib.RongCallCommon;
import io.rong.calllib.RongCallSession;
import io.rong.common.RLog;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.GroupNotificationMessage;
import io.rong.message.InformationNotificationMessage;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 通用数据处理
 * 包含一些公共请求及数据处理
 *
 * @author fly
 * @date 2018-06-20
 */
public class CDataProcessor {

    private static AMapLocationItem sMapLocationCache;

    /**
     * 连接融云成功并发出收新消息通知
     */
    public static void connectRCServer() {
        if (RcConnector.isConnected()) {
            Logger.e("融云服务已连接");
            return;
        }
        CDataProcessor.connectRCServer(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new MessageNotifyEvent(DataType.CONNECT_NOTIFY_MSG));
            }
        });
    }

    /**
     * 链接融云服务器
     */
    private static void connectRCServer(final Runnable successRunnable) {
        RcConnector.OnConnectStatusListener listener = new RcConnector.OnConnectStatusListener() {
            @Override
            public void onSuccess(String userId, String token) {
                RcUser.getInstance().setToken(token);
                if (successRunnable != null) {
                    successRunnable.run();
                }
            }

            @Override
            public void onFailure(RongIMClient.ErrorCode errorCode) {

            }
        };
        if (!TextUtils.isEmpty(RcUser.getInstance().getToken())) {
            RcConnector.connect(RcUser.getInstance().getToken(), listener);
        } else {
            RcConnector.getTokenAndConnect(RcUser.getInstance().getUserId(), listener);
        }
    }

    /**
     * 同步用户信息
     */
    public static void syncUserInfo() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_PERSONAL_INFO)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(ApUtils.getApp().toString(), new OkCallback<UserInfoResponse>() {
                    @Override
                    public void onResponse(UserInfoResponse response, String srcData) {
                        if (response.isSuccess()) {
                            RcUser.getInstance().setInfoResponse(response);
                        }
                    }
                });
    }

    /**
     * 同步好友ids
     */
    public static void syncFriendIds() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_FRIEND_USERID_LIST)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(ApUtils.getApp().toString(), new OkCallback<FriendIdResponse>() {
                    @Override
                    public void onResponse(FriendIdResponse response, String srcData) {
                        if (response.isSuccess()) {
                            DataManager.saveAllFriendIds(response.getFriendIdList());
                        }
                    }
                });
    }

    /**
     * 同步聊天礼物
     *
     * @param runnable
     */
    public static void syncChatGifts(final Runnable runnable) {
        OkRequest.getInstance().withUrl(UrlConfig.GET_GIFT_LIST)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(ApUtils.getApp().toString(), new OkCallback<ChatGiftResponse>() {
                    @Override
                    public void onResponse(ChatGiftResponse response, String srcData) {
                        if (response.isSuccess()) {
                            DataManager.saveAllChatGifts(response.getChatGiftList());
                            if (runnable != null) {
                                runnable.run();
                            }
                        }
                    }
                });
    }

    /**
     * 同步游戏种类
     *
     * @param runnable
     */
    public static void syncGameCategory(final Runnable runnable) {
        OkRequest.getInstance().withUrl(UrlConfig.GET_GAME_CATEGORY)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(GameOptionView.class.getSimpleName(), new OkCallback<GameCategoryResponse>() {
                    @Override
                    public void onResponse(GameCategoryResponse response, String srcData) {
                        if (response.isSuccess()) {
                            DataManager.saveAllGameCategorys(response.getGameCategoryList());
                            if (runnable != null) {
                                runnable.run();
                            }
                        }
                    }
                });
    }

    /**
     * 同步圈子列表
     */
    public static void syncCoteries(final Runnable runnable) {
        OkRequest.getInstance().withUrl(UrlConfig.GET_CIRCLE_LIST)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest("", new OkCallback<CoteriesResponse>() {
                    @Override
                    public void onResponse(CoteriesResponse response, String srcData) {
                        if (response.isSuccess()) {
                            DataManager.saveAllCoteries(response.getCoterieItemList());
                            if (runnable != null) {
                                runnable.run();
                            }
                        }
                    }
                });
    }

    /**
     * 设置音视频通话监听器
     */
    public static void setReceivedCallListener() {
        RongCallClient.setReceivedCallListener(new IRongReceivedCallListener() {
            @Override
            public void onReceivedCall(final RongCallSession callSession) {
                RLog.d("VoIPReceiver", "onReceivedCall");
                if (GameRunningTextActivity.GAME_TAG.equals(callSession.getExtra())) {
                    //游戏中的音视频
                    EventBus.getDefault().post(new GameMediaEvent(callSession.getMediaType(), callSession.getCallId()));
                } else {
                    //正常聊天音视频
                    startVoIPActivity(ApUtils.getApp(), callSession, false);
                }
            }

            @Override
            public void onCheckPermission(RongCallSession callSession) {
                RLog.d("VoIPReceiver", "onCheckPermissions");
                if (GameRunningTextActivity.GAME_TAG.equals(callSession.getExtra())) {
                    //游戏中的音视频
                    EventBus.getDefault().post(new GameMediaEvent(callSession.getMediaType(), callSession.getCallId()));
                } else {
                    //正常聊天音视频
                    startVoIPActivity(ApUtils.getApp(), callSession, true);
                }
            }
        });
    }

    /**
     * 启动通话界面
     *
     * @param context                  上下文
     * @param callSession              通话实体
     * @param startForCheckPermissions android6.0需要实时获取应用权限。
     *                                 当需要实时获取权限时，设置startForCheckPermissions为true，
     *                                 其它情况下设置为false。
     */
    private static void startVoIPActivity(Context context, final RongCallSession callSession, boolean startForCheckPermissions) {
        RLog.d("VoIPReceiver", "startVoIPActivity");
        String action;
        if (callSession.getConversationType().equals(Conversation.ConversationType.GROUP)) {
            if (callSession.getMediaType().equals(RongCallCommon.CallMediaType.VIDEO)) {
                action = RongVoIPIntent.RONG_INTENT_ACTION_VOIP_MULTIVIDEO;
            } else {
                action = RongVoIPIntent.RONG_INTENT_ACTION_VOIP_MULTIAUDIO;
            }
            Intent intent = new Intent(action);
            intent.putExtra("callSession", callSession);
            intent.putExtra("callAction", RongCallAction.ACTION_INCOMING_CALL.getName());
            if (startForCheckPermissions) {
                intent.putExtra("checkPermissions", true);
            } else {
                intent.putExtra("checkPermissions", false);
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setPackage(context.getPackageName());
            context.startActivity(intent);
        } else {
            if (callSession.getMediaType().equals(RongCallCommon.CallMediaType.VIDEO)) {
                action = RongVoIPIntent.RONG_INTENT_ACTION_VOIP_SINGLEVIDEO;
            } else {
                action = RongVoIPIntent.RONG_INTENT_ACTION_VOIP_SINGLEAUDIO;
            }
            Intent intent = new Intent(action);
            intent.putExtra("callSession", callSession);
            intent.putExtra("callAction", RongCallAction.ACTION_INCOMING_CALL.getName());
            if (startForCheckPermissions) {
                intent.putExtra("checkPermissions", true);
            } else {
                intent.putExtra("checkPermissions", false);
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setPackage(context.getPackageName());
            context.startActivity(intent);
        }
    }

    /**
     * 请求好友关系
     *
     * @param targetId
     */
    public static void sendFriendRelationRequest(final String targetId) {
        OkRequest.getInstance().withUrl(UrlConfig.QUERY_IS_FRIEND).withRequest(new RelationRequest(RcUser.getInstance().getUserId()
                , targetId)).doRequest(PrivateMessageActivity.class.getSimpleName(), new OkCallback<BlnResponse>() {
            @Override
            public void onResponse(BlnResponse friendRelationResponse, String srcData) {
                EventBus.getDefault().post(new FriendRelationEvent(FriendRelationEvent.QUERY
                        , friendRelationResponse.isBln()));
            }
        });
    }


    /**
     * 同意或拒绝好友申请
     *
     * @param targetId
     * @param dealType
     * @param adapterPosition
     */
    public static void dealFriendRequest(final int dealType, final String targetId, final int adapterPosition) {
        OkRequest.getInstance().withUrl(UrlConfig.FRIEND_RELATION_HANDLE)
                .withRequest(new FriendRelationRequest(RcUser.getInstance().getUserId(), targetId, dealType))
                .doRequest(PrivateMessageActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {

                    @Override
                    public void onResponse(BaseResponse baseResponse, String srcData) {
                        if (baseResponse.isSuccess()) {
                            if (dealType == DataType.FRIEND_DEAL_AGREE) {
                                //同意
                                deleteAllFriendApplyMessage(targetId);
                                insertFriendStatusMessage(targetId, DataType.FRIEND_ALLOW
                                        , ApUtils.getApp().getString(R.string.apply_add_friend_agree), null);
                                EventBus.getDefault().post(new FriendRelationEvent(FriendRelationEvent.AGREE, true));
                                //重新同步好友UserId列表
                                CDataProcessor.syncFriendIds();
                            } else if (dealType == DataType.FRIEND_DEAL_REFUSE) {
                                //拒绝
                                deleteAllFriendApplyMessage(targetId);
                                insertFriendStatusMessage(targetId, DataType.FRIEND_REFUSE
                                        , ApUtils.getApp().getString(R.string.apply_add_friend_refuse), null);
                                EventBus.getDefault().post(new FriendRelationEvent(FriendRelationEvent.REJECT, false));
                            } else if (dealType == DataType.FRIEND_DEAL_DELETE) {
                                //删除
                                RefreshEvent event = new RefreshEvent(DataType.REFRESH_DELETE_FRIEND);
                                event.extraInt = adapterPosition;
                                EventBus.getDefault().post(event);
                            }
                        }
                    }
                });
    }

    /**
     * 同意或拒绝好友申请
     *
     * @param msgId
     * @param targetId
     * @param dealType
     * @param adapter
     */
    public static void dealFriendRequest(final int msgId, final String targetId, final int dealType, final MsgListAdapter adapter) {
        OkRequest.getInstance().withUrl(UrlConfig.FRIEND_RELATION_HANDLE)
                .withRequest(new FriendRelationRequest(RcUser.getInstance().getUserId(), targetId, dealType))
                .doRequest(PrivateMessageActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {

                    @Override
                    public void onResponse(BaseResponse baseResponse, String srcData) {
                        if (baseResponse.isSuccess()) {
                            if (dealType == DataType.FRIEND_DEAL_AGREE) {
                                //同意
                                deleteLocalMessage(msgId, adapter);
                                insertFriendStatusMessage(targetId, DataType.FRIEND_ALLOW
                                        , ApUtils.getApp().getString(R.string.apply_add_friend_agree), adapter);
                                EventBus.getDefault().post(new FriendRelationEvent(FriendRelationEvent.AGREE, true));
                                //重新同步好友UserId列表
                                CDataProcessor.syncFriendIds();
                            } else if (dealType == DataType.FRIEND_DEAL_REFUSE) {
                                //拒绝
                                deleteLocalMessage(msgId, adapter);
                                insertFriendStatusMessage(targetId, DataType.FRIEND_REFUSE
                                        , ApUtils.getApp().getString(R.string.apply_add_friend_refuse), adapter);
                                EventBus.getDefault().post(new FriendRelationEvent(FriendRelationEvent.REJECT, false));
                            } else if (dealType == DataType.FRIEND_DEAL_DELETE) {
                                //删除
                            }
                        }
                    }
                });
    }

    /**
     * 发送添加好友消息
     */
    public static void sendAddFriendMsgRequest(final String targetId, final MsgListAdapter adapter) {
        OkRequest.getInstance().withUrl(UrlConfig.ADD_FRIEND)
                .withRequest(new RelationRequest(RcUser.getInstance().getUserId(), targetId))
                .doRequest(PrivateMessageActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse baseResponse, String srcData) {
                        if (baseResponse.isSuccess()) {
                            EventBus.getDefault().post(new FriendRelationEvent(FriendRelationEvent.APPLY, false));
                            insertFriendStatusMessage(targetId, DataType.FRIEND_SENT
                                    , ApUtils.getApp().getString(R.string.apply_add_friend_sent), adapter);
                        } else {
                            Toasty.showNormal("发送添加好友消息失败");
                        }
                    }
                });
    }

    /**
     * 插入一条创建群聊成功的事件消息
     *
     * @param targetId
     * @param data
     */
    public static void insertGroupCreateNotificationMessage(String targetId, String data) {
        GroupNotificationMessage message = GroupNotificationMessage.obtain(RcUser.getInstance().getUserId(),
                GroupNotificationMessage.GROUP_OPERATION_CREATE, data, data);
        RcImMgr.getInstance().insertMessage(Conversation.ConversationType.GROUP, targetId, message, new RongIMClient.ResultCallback<Message>() {
            @Override
            public void onSuccess(Message message) {
                EventBus.getDefault().post(new MessageNotifyEvent(DataType.COMMON_NOTIFY_MSG));
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    /**
     * 插入一条拉人和踢人消息
     *
     * @param targetId
     * @param notificationMsg
     */
    public static void insertInviteKickStatusMessage(String targetId, InformationNotificationMessage notificationMsg) {
        RcImMgr.getInstance().insertMessage(Conversation.ConversationType.GROUP, targetId, notificationMsg, new RongIMClient.ResultCallback<Message>() {
            @Override
            public void onSuccess(Message message) {
                Logger.e("插入拉人和踢人消息成功");
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    /**
     * 插入一条好友状态消息
     *
     * @param targetId
     * @param status
     * @param content
     * @param mAdapter
     */
    public static void insertFriendStatusMessage(String targetId, int status, String content, final MsgListAdapter mAdapter) {
        FriendAddMessage message = FriendAddMessage.obtain(status, content);
        RcImMgr.getInstance().insertMessage(Conversation.ConversationType.PRIVATE, targetId, message, new RongIMClient.ResultCallback<Message>() {
            @Override
            public void onSuccess(Message message) {
                if (mAdapter != null) {
                    mAdapter.addToStart(new LMessage(message), false);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    /**
     * 删除本地消息并刷新列表
     *
     * @param msgId
     * @param mAdapter
     */
    public static void deleteLocalMessage(final int msgId, final MsgListAdapter mAdapter) {
        RcImMgr.getInstance().deleteMessage(new int[]{msgId}, new RongIMClient.ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                if (mAdapter != null) {
                    mAdapter.deleteById(msgId);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    /**
     * 删除所有添加好友申请的消息
     *
     * @param targetId
     */
    public static void deleteAllFriendApplyMessage(String targetId) {
        RcImMgr.getInstance().searchMessages(Conversation.ConversationType.PRIVATE, targetId
                , FriendAddMessage.OBJECT_NAME, new RongIMClient.ResultCallback<List<Message>>() {

                    @Override
                    public void onSuccess(List<Message> messages) {
                        final List<Integer> delMsgIds = new ArrayList<>();
                        for (Message locMsg : messages) {
                            if (locMsg.getContent() instanceof FriendAddMessage
                                    && ((FriendAddMessage) locMsg.getContent()).getStatus() == DataType.FRIEND_APPLY) {
                                //删除所有待申请的记录
                                delMsgIds.add(locMsg.getMessageId());
                            }
                        }
                        if (delMsgIds.isEmpty()) {
                            return;
                        }

                        final int[] msgIds = new int[delMsgIds.size()];
                        for (int i = 0; i < delMsgIds.size(); i++) {
                            msgIds[i] = delMsgIds.get(i);
                        }
                        RcImMgr.getInstance().deleteMessage(msgIds, new RongIMClient.ResultCallback<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {
                            }
                        });
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                    }
                });
    }

    /**
     * 删除待申请的添加好友消息后插入一条
     *
     * @param newMessage
     */
    public static void insertFriendMessageAfterDeleteAll(final Message newMessage) {
        RcImMgr.getInstance().searchMessages(Conversation.ConversationType.PRIVATE, newMessage.getTargetId(), FriendAddMessage.OBJECT_NAME, new RongIMClient.ResultCallback<List<Message>>() {
            @Override
            public void onSuccess(List<Message> messages) {
                final List<Integer> delMsgIds = new ArrayList<>();
                for (Message locMsg : messages) {
                    if (locMsg.getContent() instanceof FriendAddMessage
                            && ((FriendAddMessage) locMsg.getContent()).getStatus() == DataType.FRIEND_APPLY) {
                        //删除所有待申请的记录
                        delMsgIds.add(locMsg.getMessageId());
                    }
                }
                if (delMsgIds.isEmpty()) {
                    insertNewFriendMessage(new int[]{});
                    return;
                }

                final int[] msgIds = new int[delMsgIds.size()];
                for (int i = 0; i < delMsgIds.size(); i++) {
                    msgIds[i] = delMsgIds.get(i);
                }
                RcImMgr.getInstance().deleteMessage(msgIds, new RongIMClient.ResultCallback<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        if (aBoolean) {
                            insertNewFriendMessage(msgIds);
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }

            public void insertNewFriendMessage(final int[] msgIds) {
                RongIMClient.getInstance().insertMessage(Conversation.ConversationType.PRIVATE
                        , newMessage.getTargetId(), newMessage.getSenderUserId(),
                        newMessage.getContent(), TimeUtils.getNowMills(), new RongIMClient.ResultCallback<Message>() {
                            @Override
                            public void onSuccess(Message message) {
                                RefreshMessageEvent event = new RefreshMessageEvent();
                                event.delMsgIds = msgIds;
                                event.newMessage = message;
                                EventBus.getDefault().post(event);
                                if (newMessage.getContent() instanceof FriendAddMessage) {
                                    if (((FriendAddMessage) newMessage.getContent()).getStatus() == DataType.FRIEND_ALLOW) {
                                        EventBus.getDefault().post(new FriendRelationEvent(FriendRelationEvent.AGREE, true));
                                    }
                                }
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {

                            }
                        });
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    /**
     * 通知未知消息更新
     */
    public static void postNewFriendMsgUnreadCount() {
        MessageCountEvent event = new MessageCountEvent();
        event.setCount(DataManager.getAllFriendMessageCountByUserId(RcUser.getInstance().getUserId()));
        event.setType(MessageCountEvent.NEW_FRIEND_MESSAGE);
        EventBus.getDefault().post(event);
    }

    /**
     * 启动签到定位并上传数据
     */
    public static void startUploadLocation() {
        if (!EasyPermissions.hasPermissions(ApUtils.getApp(), Manifest
                .permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)) {
            Logger.e("无定位权限不上传位置信息");
            return;
        }
        final GDLocation gaoDeLocation = new GDLocation(ApUtils.getApp(), AMapLocationClientOption.AMapLocationPurpose.SignIn);
        gaoDeLocation.startLocation(new GDLocation.LocationCallback() {
            @Override
            public void onResult(AMapLocation aMapLocation) {
                //停止并销毁定位服务
                gaoDeLocation.stopLocation();
                gaoDeLocation.destroyLocation();
                if (aMapLocation != null) {
                    //上传定位数据
                    setMapLocationCache(aMapLocation);
                    uploadLocation(aMapLocation);
                }
            }

            /**
             * 上报定位信息
             * @param aMapLocation
             */
            private void uploadLocation(AMapLocation aMapLocation) {
                UploadLocationRequest request = new UploadLocationRequest();
                request.setUserId(RcUser.getInstance().getUserId());
                request.setAdCode(aMapLocation.getAdCode());
                request.setAddress(aMapLocation.getAddress());
                request.setCity(aMapLocation.getCity());
                request.setCityCode(aMapLocation.getCityCode());
                request.setDistrict(aMapLocation.getDistrict());
                request.setProvince(aMapLocation.getProvince());
                request.setLatitude(aMapLocation.getLatitude());
                request.setLongitude(aMapLocation.getLongitude());
                OkRequest.getInstance().withUrl(UrlConfig.UPLOAD_LOCATION).withRequest(request)
                        .doRequest(ApUtils.getApp().getClass().getSimpleName(), new OkCallback<BaseResponse>() {
                            @Override
                            public void onResponse(BaseResponse response, String srcData) {
                                Logger.e("定位信息上报结果：" + response.getMessage());
                            }
                        });
            }
        });
    }

    /**
     * 获取最新的高德定位
     *
     * @param callback
     */
    public static void getLatestLocation(GDLocation.LocationCallback callback) {
        new GDLocation(ApUtils.getApp(), AMapLocationClientOption
                .AMapLocationPurpose.SignIn).startLocation(callback);
    }

    /**
     * 点赞或取消点赞
     *
     * @param vpcCount   计数实体
     * @param postPkId   帖子id
     * @param praiseType 点赞类型
     */
    public static void doTopicPraise(final SpcCount vpcCount, String postPkId, int praiseType) {
        PostLikeRequest request = new PostLikeRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPostPkId(postPkId);
        request.setLikeType(praiseType);
        OkRequest.getInstance().withUrl(vpcCount.isLikeBln() ? UrlConfig.ADD_POST_LIKE : UrlConfig.CANCEL_POST_LIKE)
                .withRequest(request).doRequest(vpcCount.getClass().getSimpleName(), null);
    }

    /**
     * 设置定位缓存
     *
     * @param aMapLocation
     */
    public static void setMapLocationCache(AMapLocation aMapLocation) {
        CDataProcessor.sMapLocationCache = new AMapLocationItem(aMapLocation);
    }

    /**
     * 获取定位缓存
     *
     * @return
     */
    public static AMapLocationItem getMapLocationCache() {
        return sMapLocationCache;
    }

    /**
     * 检查更新
     *
     * @param context
     * @param showDialog 是否弹窗
     */
    public static void checkAppUpdate(Context context, boolean showDialog, boolean clearHint) {
        OkRequest.getInstance().withUrl(UrlConfig.CHECK_APP_UPDATE)
                .withRequest(new AppUdateRequest(AppUtils.getAppVersionName()))
                .doRequest("", new OkCallback<AppUpdateResponse>() {
                    @Override
                    public void onResponse(AppUpdateResponse response, String srcData) {
                        if (response.isSuccess()) {
                            boolean hasNew = response.getIsUpVersion() > DataType.APP_NO_UPDATE;
                            if (hasNew && showDialog) {
                                new AppUpdateDialog(context, new AppUpdateItem(response
                                        , context.getExternalCacheDir().toString().toLowerCase())).show();
                            } else if (!hasNew && showDialog) {
                                Toasty.showNormal(R.string.version_latest);
                            } else if (hasNew) {
                                //发现新版本
                                AppUpdateEvent event = new AppUpdateEvent();
                                event.newVersionNum = response.getVersionNum();
                                event.updateStatus = DataType.APP_UPDATE;
                                EventBus.getDefault().post(event);
                            }
                            if (clearHint) {
                                //清除更新提醒
                                AppUpdateEvent event = new AppUpdateEvent();
                                event.newVersionNum = response.getVersionNum();
                                event.updateStatus = DataType.APP_CLEAR_UPDATE;
                                EventBus.getDefault().post(event);
                            }
                        } else if (showDialog) {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 退出重新登录
     *
     * @param activity
     */
    public static void quitAppAndReLogin(Activity activity, boolean launchLogin) {
        RcConnector.logout();
        RcUser rcUser = RcUser.getInstance();
        rcUser.deleteAuthorize(activity);
        rcUser.clearUser();
        if (launchLogin) {
            ActivityUtils.finishAllActivities(true);
            ActivityUtils.startActivity(LoginActivity.class);
        }
    }

    /**
     * 清空消息列表
     *
     * @param msgType 消息清空类别
     */
    public static void clearMsgContentByType(int msgType, String reqTag, Runnable refreshCallback) {
        OkRequest.getInstance().withUrl(UrlConfig.CLEAR_MSG_LIST)
                .withRequest(new ClearMsgRequest(RcUser.getInstance().getUserId(), msgType))
                .doRequest(reqTag, new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            refreshCallback.run();
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 检查是否已同步缓存了对外的userPkId
     */
    public static void checkSyncUserPkId() {
        if (!TextUtils.isEmpty(RcUser.getInstance().getUserPkId())) {
            return;
        }
        convertUserId2UserPkId(RcUser.getInstance().getUserId(), new OkCallback<ConvertUidResponse>() {
            @Override
            public void onResponse(ConvertUidResponse convertUidResponse, String srcData) {
                if (convertUidResponse.isSuccess()) {
                    RcUser.getInstance()
                            .setUserPkId(convertUidResponse.getObjId())
                            .applyUser();
                }
            }
        });
    }

    /**
     * userId转换成userPkId
     *
     * @param userId
     * @param callback
     */
    public static void convertUserId2UserPkId(String userId, OkCallback<ConvertUidResponse> callback) {
        OkRequest.getInstance().withUrl(UrlConfig.CONVERT_USER_ID)
                .withRequest(new ConvertUidRequest(1, userId))
                .doRequest(UrlConfig.CONVERT_USER_ID, callback);
    }

    /**
     * userPkId转换成userId
     *
     * @param userPkId
     * @param callback
     */
    public static void convertUserPkId2UserId(String userPkId, OkCallback<ConvertUidResponse> callback) {
        OkRequest.getInstance().withUrl(UrlConfig.CONVERT_USER_ID)
                .withRequest(new ConvertUidRequest(2, userPkId))
                .doRequest(UrlConfig.CONVERT_USER_ID, callback);
    }

    /**
     * 获取特效数据
     *
     * @param effectType
     */
    public static void getEffectData(int effectType) {
        if (effectType == DataType.EFFECT_MASK
                && !EffectDataMgr.getInstance().getEffectList().isEmpty()) {
            return;
        }
        if (effectType == DataType.EFFECT_GESTURE
                && !EffectDataMgr.getInstance().getGestureList().isEmpty()) {
            return;
        }
        OkRequest.getInstance().withUrl(UrlConfig.GET_MASK_LIST)
                .withRequest(new GetMaskRequest(RcUser.getInstance().getUserId(), effectType))
                .doRequest(SingleVideoCallActivity.class.getSimpleName(), new OkCallback<GetMaskResponse>() {
                    @Override
                    public void onResponse(GetMaskResponse response, String srcData) {
                        if (response.isSuccess()) {
                            //添加无道具项
                            List<Mask> effects = new ArrayList<>();
                            Mask noMask = new Mask();
                            noMask.setIconId(R.drawable.ic_delete_all);
                            noMask.setEffectType(Mask.EFFECT_TYPE_NONE);
                            effects.add(noMask);
                            for (MaskItem maskItem : response.getMaskItemList()) {
                                Mask effect = new Mask();
                                effect.setFileUrl(maskItem.getMaskUrl());
                                effect.setIconUrl(maskItem.getMaskPicUrl());
                                effect.setEffectType(Mask.EFFECT_TYPE_NORMAL);
                                effects.add(effect);
                            }
                            if (effectType == DataType.EFFECT_MASK) {
                                //面具
                                EffectDataMgr.getInstance().setEffectList(effects);
                            } else if (effectType == DataType.EFFECT_GESTURE) {
                                //手势
                                EffectDataMgr.getInstance().setGestureList(effects);
                            }
                            EventBus.getDefault().post(new MaskListEvent(effects));
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

}
